import React from 'react'
import { inject, observer } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom'
import { Form, RouteLayout } from 'weaver-mobile-page'
import { List, Icon, Bubble, Select, Tools, Accordion } from 'weaver-mobile';
import { toJS } from 'mobx';
import SelectNextNode from './SelectNextNode'
import './../../../style/nextNodeOperator.less'
import base from '../../../util/base';

const ButtonGroup = RouteLayout.ButtonGroup;
const FormItem = List.FormItem;
const getLabel = Tools.getLabel;

@inject('wfNextNodeOperator')
@withRouter
@observer
export default class NextNodeOperator extends React.Component {
    componentWillMount() {
        // console.log("props",toJS(this.props))
    }
    componentDidMount() {
        const { location } = this.props;
        const { getSelectNextFlowCondition, getSelectFlowNodeInfo } = this.props.wfNextNodeOperator;
        const { params = {} } = location;
        getSelectNextFlowCondition(params);
    }
    componentWillUnmount() {
        const { reset } = this.props.wfNextNodeOperator;
        reset();
    }
    getItems = () => {
        const { form, nextNodeParams, canSubmit, operatorChangeDisable, groupList, nodeAttribute, selectedNodeId, nodeInfoMap} = this.props.wfNextNodeOperator;
        const { isInit } = form;
        const fields = [];

        if (isInit) {

            let nodeName = '';
            selectedNodeId.split(',').map((key) => {
                let nodeInfo = nodeInfoMap[key];
                if (nodeInfo) {
                    nodeName += "   " + nodeInfo.nodeName;
                }
            });
            if(nodeName != '') {
                nodeName = nodeName.substring(1);
            }

            groupList.map((group, index) => {
                let items = [];
                let conditioninfo = toJS(group.items);
                let title = group.title;

                conditioninfo.forEach((field) => {

                    if (field.domkey[0] === 'nextNode') {
                        items.push(
                            <div className="formItem"
                                key={field.domkey.join('__')}
                                onClick={() => {
                                    const { history, wfNextNodeOperator } = this.props;
                                    const { layout } = wfNextNodeOperator;
                                    history.push(layout.path)
                                }}>
                                <FormItem
                                    key={field.domkey.join('__')}
                                    label={field.label}
                                    extra={<Icon type="right" />}
                                    required={nodeName?false:true}
                                    line={true}
                                >{nodeName ? nodeName : getLabel(18214,"请选择")}</FormItem></div>
                        );
                    }
                    if (field.domkey[0].indexOf("nodeOperator_") > -1) {
                        items.push(
                            <Form.Item
                            key={field.domkey.join('__')}
                            form={form}
                            fieldConfig={field}
                            onChange={this.onChange}
                        />);
                    }
                    if (field.domkey[0].indexOf("SignType_") > -1 && operatorChangeDisable != '1') {
                        items.push(<Form.Item
                            key={field.domkey.join('__')}
                            form={form}
                            fieldConfig={field}
                            onChange={this.onChange}
                        />);
                    }
                    if (field.domkey[0].indexOf("ccOperator_") > -1) {
                        items.push(
                            <Form.Item
                            key={field.domkey.join('__')}
                            form={form}
                            fieldConfig={field}
                            onChange={this.onChange}
                        />);
                    }
                    if (field.domkey[0].indexOf("canSubmit_") > -1 && operatorChangeDisable != '1') {
                        items.push(<Select
                            value={canSubmit}
                            label={getLabel(500275, "意见选择")}
                            key={field.domkey.join('__')}
                            viewAttr={3}
                            options={field.options}
                            active={true}
                            onChange={(key, showname) => {
                                const { setResultData } = this.props.wfNextNodeOperator;
                                setResultData({ canSubmit: { value: key } });
                                this.onChange(field, { value: key });
                            }}
                        />
                        )
                    }
                });
                if(nodeAttribute == '1') {
                    fields.push(
                        <Accordion defaultActiveKey="0" className="my-accordion">
                            <Accordion.Panel className='my-accordion-panel' header={title}>
                                {items}
                            </Accordion.Panel>
                        </Accordion>
                    )
                } else {
                    fields.push(
                        <div>
                            {items}
                        </div>
                    )
                }
            })
        }
        return fields;
    }
    onChange = (condition, value) => {
        const { form, nextNodeOperator, setResultData } = this.props.wfNextNodeOperator;
        setResultData({ [condition.domkey[0]]: value||"" })
        form.onChange(condition, value);
    }
    render() {
        const { layout, cancelFunc, form } = this.props.wfNextNodeOperator;
        let buttonGroupData = [
            {
                key: 'clear',
                text: getLabel(201,'取消'),
                onClick: () => {
                    this.props.history.go(-1);
                    cancelFunc && cancelFunc();
                },
            },
            {
                key: 'submit',
                text: getLabel(826,'确定'),
                onClick: () => { 
                    const { resultDatas, doSubmitReady, getResultParams , verification} = this.props.wfNextNodeOperator;
                    const { changeSubmitParam } = base.wfOperateStore;
                    let result = getResultParams();
                    verification(result, () => { //验证通过，执行回调函数
                        changeSubmitParam(result);
                        doSubmitReady({ src: "submit", actiontype: "requestOperation", isSelectNextFlow: '1'});//...nextNodeParams 
                        this.props.history.go(-1);
                    })//验证是否能提交

                   
                },
                type: 'primary',
            },
        ];
        let buttonGroupData_layout = [
            {
                key: 'reset',
                text: getLabel(311,'清除'),
                onClick: () => { 
                    const { getDefaultDatas, clearFormData, setdefaultnodeids } = this.props.wfNextNodeOperator;
                    setdefaultnodeids();
                    clearFormData();
                    this.props.history.go(-1);
                 },
            },
            {
                key: 'submit',
                text: getLabel(826, '确定'),
                onClick: () => {
                    const { list, setNextNodeParams,setdefaultnodeids } = this.props.wfNextNodeOperator;
                    if (list.selectedRowKeys.length === 0) {
                        Bubble.warning(getLabel(500320,"必须选择下一个节点"), 2);
                    } else {
                        if(this.checkSelectedNodes(list.selectedRowKeys)) {
                            setdefaultnodeids(list.selectedRowKeys.join(','));
                            setNextNodeParams();
                            this.props.history.go(-1);
                        }
                    }
                },
                type: 'primary',
            },
        ];
        return (
            <div className="wf-form-nextNodeOperator">
                <div className="wf-form-nextNodeOperator-title"><span>{getLabel(500321,"请选择下一节点操作者")}</span></div>
                <Form store={form} className={'wf-form-nextNodeOperator-form'}>
                    <List>
                        {this.getItems()}
                    </List>
                </Form>
                <div>
                    <ButtonGroup data={buttonGroupData} />
                </div>
                {<Route
                    key={layout.id}
                    path={layout.path}
                    render={() => (
                        <RouteLayout>
                            <div
                                key="wmPoutePageDemo"
                                className="wm-route-layout"
                            >
                                <SelectNextNode />
                                <ButtonGroup data={buttonGroupData_layout} />
                            </div>
                        </RouteLayout>
                    )}
                />}
            </div>
        )
    }


    // 检查选择的节点类型
    checkSelectedNodes(checkNodeIds) {
        const { nodeInfoMap, branchNodesMap } = this.props.wfNextNodeOperator;
        if (checkNodeIds.length > 1) {
            let isAllTrunkNode = true;//是否全是主干节点
            let isAllDiffBranchNode = true;//是否全为不同分支分叉中间点
            let branchMarks = [];
            checkNodeIds.map((nodeid) => {
                //为主干节点
                if (nodeInfoMap[nodeid] && nodeInfoMap[nodeid].nodeAttribute != '2') {
                    isAllDiffBranchNode = false;
                } else {
                    //分叉中间点
                    isAllTrunkNode = false;

                    Object.keys(branchNodesMap).map(key => {
                        if(branchNodesMap[key].indexOf(nodeid) > -1) {
                            if(branchMarks.indexOf(key) > -1) {//节点在相同的分支
                                isAllDiffBranchNode = false;
                            } else {//记录分支标识
                                branchMarks.push(key);
                            }
                        }
                    })
                }
            });

            //选择的节点全为主干节点，且选择了多个
            if(isAllTrunkNode) {
                Bubble.warning(getLabel(525840,"非分叉中间点只能选择一个"), 2);
                return false;
            }

            //不全为不同分支分叉中间点
            if(!isAllDiffBranchNode) {
                Bubble.warning(getLabel(525841,"选择的多个节点必须为不同分支的分叉中间点"), 2);
                return false;
            }
        }
        return true;
    }
}